<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900">学习进度管理</h1>
        <p class="mt-2 text-gray-600">查看和管理所有学生的学习进度</p>
      </div>

      <!-- 搜索区域 -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-8">
        <div class="flex flex-col sm:flex-row gap-4">
          <div class="flex-1">
            <label for="search" class="block text-sm font-medium text-gray-700 mb-2">
              搜索学生
            </label>
            <input
              id="search"
              v-model="searchQuery"
              type="text"
              placeholder="输入学生姓名或用户名..."
              class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @input="handleSearch"
            />
          </div>
          <div class="flex items-end">
            <button
              @click="loadAllProgress"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
            >
              刷新数据
            </button>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-8">
        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <p class="mt-2 text-gray-600">加载中...</p>
      </div>

      <!-- 学生进度列表 -->
      <div v-else-if="filteredStudents.length > 0" class="space-y-6">
        <div
          v-for="student in filteredStudents"
          :key="student.id"
          class="bg-white rounded-lg shadow-sm p-6"
        >
          <!-- 学生信息 -->
          <div class="flex items-center justify-between mb-4">
            <div>
              <h3 class="text-lg font-semibold text-gray-900">{{ student.name }}</h3>
              <p class="text-sm text-gray-600">用户ID: {{ student.id }}</p>
              <p class="text-sm text-gray-600">邮箱: {{ student.email }}</p>
            </div>
            <div class="text-right">
              <p class="text-sm text-gray-600">总进度</p>
              <p class="text-2xl font-bold text-blue-600">{{ student.totalProgress }}%</p>
            </div>
          </div>

          <!-- 章节进度 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            <div
              v-for="chapter in student.chapters"
              :key="chapter.chapter"
              class="bg-gray-50 rounded-lg p-4"
            >
              <h4 class="font-medium text-gray-900 mb-2">第{{ chapter.chapter }}章</h4>
              <div class="space-y-2">
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">视频观看</span>
                  <span class="font-medium">{{ chapter.videoProgress }}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div
                    class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                    :style="{ width: chapter.videoProgress + '%' }"
                  ></div>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">资料阅读</span>
                  <span class="font-medium">{{ chapter.materialProgress }}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div
                    class="bg-green-600 h-2 rounded-full transition-all duration-300"
                    :style="{ width: chapter.materialProgress + '%' }"
                  ></div>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-gray-600">练习完成</span>
                  <span class="font-medium">{{ chapter.exerciseProgress }}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div
                    class="bg-purple-600 h-2 rounded-full transition-all duration-300"
                    :style="{ width: chapter.exerciseProgress + '%' }"
                  ></div>
                </div>
              </div>
            </div>
          </div>

          <!-- 最近活动 -->
          <div v-if="student.recentActivities && student.recentActivities.length > 0" class="mt-6">
            <h4 class="font-medium text-gray-900 mb-3">最近活动</h4>
            <div class="space-y-2">
              <div
                v-for="activity in student.recentActivities.slice(0, 3)"
                :key="activity.id"
                class="flex items-center justify-between py-2 px-3 bg-gray-50 rounded"
              >
                <div class="flex items-center space-x-3">
                  <div
                    class="w-2 h-2 rounded-full"
                    :class="{
                      'bg-blue-500': activity.actionType === 'video_watch',
                      'bg-green-500': activity.actionType === 'material_click',
                      'bg-purple-500': activity.actionType === 'exercise_complete',
                      'bg-gray-500': activity.actionType === 'page_visit'
                    }"
                  ></div>
                  <span class="text-sm text-gray-700">{{ getActionTypeText(activity.actionType) }}</span>
                  <span class="text-sm text-gray-500">第{{ activity.chapter }}章</span>
                </div>
                <span class="text-xs text-gray-500">{{ formatDate(activity.createdAt) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 无数据状态 -->
      <div v-else class="text-center py-12">
        <div class="text-gray-400 mb-4">
          <svg class="mx-auto h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
        </div>
        <h3 class="text-lg font-medium text-gray-900 mb-2">暂无学生数据</h3>
        <p class="text-gray-600">{{ searchQuery ? '没有找到匹配的学生' : '还没有学生开始学习' }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { progressService } from '@/services/progressService'
import type { StudentProgress } from '@/types'

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const allStudents = ref<StudentProgress[]>([])

// 计算属性
const filteredStudents = computed(() => {
  if (!searchQuery.value.trim()) {
    return allStudents.value
  }
  
  const query = searchQuery.value.toLowerCase().trim()
  return allStudents.value.filter(student => 
    (student.name && student.name.toLowerCase().includes(query)) ||
    (student.email && student.email.toLowerCase().includes(query)) ||
    student.id.toString().includes(query)
  )
})

// 方法
const loadAllProgress = async () => {
  loading.value = true
  try {
    const data = await progressService.getAggregatedProgress()
    allStudents.value = data
  } catch (error) {
    console.error('加载学生进度失败:', error)
    // 这里可以添加错误提示
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

const getActionTypeText = (actionType: string): string => {
  const actionMap: Record<string, string> = {
    'video_watch': '观看视频',
    'material_click': '阅读资料',
    'exercise_complete': '完成练习',
    'page_visit': '访问页面'
  }
  return actionMap[actionType] || actionType
}

const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMins = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffMins < 1) {
    return '刚刚'
  } else if (diffMins < 60) {
    return `${diffMins}分钟前`
  } else if (diffHours < 24) {
    return `${diffHours}小时前`
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

// 生命周期
onMounted(() => {
  loadAllProgress()
})
</script>

<style scoped>
/* 自定义样式 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>